/**
 * 试剂架示意图
 */
import { FC, useEffect, useMemo, useState } from "react";
import { observer, inject } from "mobx-react";
import { Popover, Space, Typography, Modal, Form, InputNumber } from "antd";
import { ITStore } from "../../store";
import { ITShelfBottleInfo } from "../../store/interfaces";
import {
  createList,
  ROWWORD,
  computeFontSize,
  coputeBorderWide,
  computeBottleXY,
} from "../../utils";

import "./index.less";

type TProp = {
  store: ITStore;
  setBottleListInfo: (data: any) => void;
  bottleListInfo: any;
  close?: () => void;
  slotName?: string;
};

type TPosi = {
  x: number;
  y: number;
};

type TPopCnt = {
  slotName: string;
  bottleListInfo?: any[];
};

const { Text } = Typography;

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

const SlotModal: FC<TProp | any> = inject("store")(
  observer(({ store, slotName, close }: TProp) => {
    const {
      languageStore: { lang },
      shelfStore: { currentShelfPlane, changeCurrentShelfPlane },
    } = store;

    const [form] = Form.useForm();

    // const [bottleInfo, setBottleInfo] = useState<ITShelfBottleInfo | null>(
    //   null
    // );

    const { bottleList } = currentShelfPlane;

    useEffect(() => {
      let bottleInfo: any = null;
      bottleList?.some((item) => {
        if (item.name === slotName) {
          bottleInfo = item as ITShelfBottleInfo;
          return true;
        }
        return false;
      });
      if (bottleInfo) {
        form.setFieldsValue({
          x: bottleInfo.x || bottleInfo.autox,
          y: bottleInfo.y || bottleInfo.autoy,
        });
      }
    }, [bottleList, form, slotName]);

    const closeModa = () => {
      if (close) {
        close();
      }
    };

    const formFinish = async (values: TPosi) => {
      bottleList?.some((item) => {
        if (item.name === slotName) {
          item.x = values.x;
          item.y = values.y;
          return true;
        }
        return false;
      });
      changeCurrentShelfPlane({
        bottleList,
      });
      closeModa();
    };

    return (
      <Modal
        title={slotName}
        open={!!slotName}
        destroyOnClose={true}
        onOk={() => {
          form.submit();
        }}
        confirmLoading={false}
        onCancel={closeModa}
      >
        <Form {...layout} form={form} name="bottleForm" onFinish={formFinish}>
          <Form.Item name="x" label="x" rules={[{ required: true }]}>
            <InputNumber
              addonAfter={lang["langmmunit"]}
              style={{ width: "100%" }}
            />
          </Form.Item>
          <Form.Item name="y" label="y" rules={[{ required: true }]}>
            <InputNumber
              addonAfter={lang["langmmunit"]}
              style={{ width: "100%" }}
            />
          </Form.Item>
        </Form>
      </Modal>
    );
  })
);

const ShelfPlane: FC<TProp | any> = ({
  store,
  setBottleListInfo,
  bottleListInfo,
}: TProp): JSX.Element => {
  const {
    languageStore: { lang },
    shelfStore: { currentShelfPlane },
    globalStore: { mmPixRate },
  } = store;

  const { diameter } = currentShelfPlane;

  // 试剂架长度
  const [shelfLength, setShelfLength] = useState<number>(0);

  // 试剂架宽度
  const [shelfWide, setShelfWide] = useState<number>(0);

  // 横向偏移
  const [shelfOffsetx, setShelfOffsetx] = useState<number>(0);

  // 纵向偏移
  const [shelfOffsety, setShelfOffsety] = useState<number>(0);

  // 行数
  const [shelfRow, setShelfRow] = useState<number[]>([]);

  // 列数
  const [shelfColumn, setShelfColumn] = useState<number[]>([]);

  // 行间距
  const [shelfRowSpace, setShelfRowSpace] = useState<number>(0);

  // 列间距
  const [shelfColSpace, setShelfColSpace] = useState<number>(0);

  // 形状
  const [shelfShape, setShelfShape] = useState<string | undefined>(undefined);

  // 直径
  const [shelfDiameter, setShelfDiameter] = useState<number>(0);

  // 字体大小
  const [slotFontSize, setSlotFontSize] = useState<number>(12);

  // 瓶子粗细
  const [slotWide, setSlotWide] = useState<number>(4);

  // 修改瓶子坐标弹窗
  const [editSlotName, setEditSlotName] = useState<string | null>(null);

  const PopContent = ({ slotName, bottleListInfo }: TPopCnt) => {
    let slotInfo: any = useMemo(() => {
      let temp: any = null;
      bottleListInfo?.some((item: ITShelfBottleInfo) => {
        if (item.name === slotName) {
          temp = item;
          return true;
        }
        return false;
      });
      return temp;
    }, [bottleListInfo, slotName]);

    return (
      <Space direction="vertical">
        <Text>
          {lang["langdiameter"]}: {slotInfo?.diameter}{" "}
          <Text type="secondary">({lang["langmmunit"]})</Text>
        </Text>
        <Text>
          x: {slotInfo?.x || slotInfo?.autox}{" "}
          <Text type="secondary">({lang["langmmunit"]})</Text>
        </Text>
        <Text>
          y: {slotInfo?.y || slotInfo?.autoy}{" "}
          <Text type="secondary">({lang["langmmunit"]})</Text>
        </Text>
      </Space>
    );
  };

  useEffect(() => {
    setSlotFontSize(computeFontSize(mmPixRate, diameter));
    setSlotWide(coputeBorderWide(mmPixRate));
  }, [mmPixRate, diameter]);

  useEffect(() => {
    const {
      length,
      wide,
      diameter,
      bottleShape,
      offsetx,
      offsety,
      row,
      column,
      rowSpace,
      columnSpace,
    } = currentShelfPlane;
    setShelfLength((length || 0) * mmPixRate);

    setShelfWide((wide || 0) * mmPixRate);

    setShelfOffsetx((offsetx || 0) * mmPixRate);

    setShelfOffsety((offsety || 0) * mmPixRate);

    setShelfRow(createList(row || 0));

    setShelfColumn(createList(column || 0));

    setShelfRowSpace((rowSpace || 0) * mmPixRate);

    setShelfColSpace((columnSpace || 0) * mmPixRate);

    setShelfShape(bottleShape);

    setShelfDiameter((diameter || 0) * mmPixRate);

    setBottleListInfo(
      computeBottleXY({
        row,
        column,
        diameter,
        offsetx,
        offsety,
        rowSpace,
        columnSpace,
      })
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentShelfPlane, mmPixRate]);

  const slotClick = (slotName: string) => {
    setEditSlotName(slotName);
  };

  const closeSlotModal = () => {
    setEditSlotName(null);
  };

  return (
    <>
      <div className="tubeplane">
        {!!shelfLength && !!shelfWide && (
          <div
            className="bord"
            style={{
              paddingLeft: shelfOffsetx,
              paddingTop: shelfOffsety,
              width: shelfLength === 0 ? "auto" : shelfLength,
              height: shelfWide === 0 ? "auto" : shelfWide,
            }}
          >
            {/* 排 */}
            {!!shelfRow.length &&
              shelfRow.map((rowItem) => {
                const rowName = ROWWORD[rowItem];
                return (
                  <div className="row" key={rowItem}>
                    {/* 列 */}
                    {!!shelfColumn.length &&
                      shelfColumn.map((colIndex) => {
                        if (shelfDiameter <= 0) {
                          return null;
                        }
                        const slotName = rowName + (colIndex + 1);
                        let borderRadius = shelfDiameter;
                        if (shelfShape === "rectangle") {
                          borderRadius = 10;
                        }
                        return (
                          <Popover
                            key={colIndex}
                            content={
                              <PopContent
                                slotName={slotName}
                                bottleListInfo={bottleListInfo}
                              />
                            }
                            title={slotName}
                          >
                            <div
                              className="col"
                              style={{
                                height: shelfDiameter,
                                width: shelfDiameter,
                                borderWidth: slotWide,
                                borderRadius,
                                marginBottom: shelfRowSpace,
                                marginRight: shelfColSpace,
                              }}
                              onClick={() => {
                                slotClick(slotName);
                              }}
                            >
                              <div
                                className="label"
                                style={{
                                  fontSize: slotFontSize,
                                }}
                              >
                                {/* 单个瓶子 */}
                                {slotName}
                              </div>
                            </div>
                          </Popover>
                        );
                      })}
                  </div>
                );
              })}
          </div>
        )}
      </div>

      <SlotModal slotName={editSlotName} close={closeSlotModal} />
    </>
  );
};

export default inject("store")(observer(ShelfPlane));
